﻿<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket Demo</title>
    <style>
        /* 整体容器 */
        .container {
            display: flex; /* 使用 flex 布局 */
            justify-content: space-between; /* 左右对齐 */
            align-items: stretch; /* 垂直拉伸 */
            height: 100vh; /* 占满整个视口高度 */
        }

        /* 左侧栏 */
        .left {
            width: 50%; /* 左侧宽度为页面的 30% */
            background-color: #f0f0f0;
            padding: 20px;
        }

        /* 右侧主内容 */
        .right {
            flex-grow: 1; /* 右侧内容充满剩余空间 */
            background-color: #dcdcdc;
            padding: 20px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="left">
            <input id="wssUrl" style="width:600px;" value="ws://192.168.66.90:15555/ws/audio-dcschat-test-debug?sn=863492053403973" />
            <button onclick="startWebSocket()">连接</button>
            <br>
            <textarea id="input_area" rows="10" cols="10" style="width:600px;height:200px;"></textarea>
            <button onclick="sendText()">发送文本</button>
            <br />
            <input type="text" id="audioUrl" style="width:300px;" placeholder="输入音频URL">
            <button onclick="playAudio()">播放</button>
            <button onclick="stopAudio()">停止播放</button>
            <button onclick="preMessage()">上一首</button>
            <button onclick="nextMessage()">下一首</button>
            <button onclick="sendVideo()">发送pcm</button>
            <br>
        </div>
        <div class="right">
            <p>输出窗口 <button onclick="clearLog()">清除日志</button></p>
            <textarea id="output_area" rows="10" cols="10" style="width:90%;height:80%;"></textarea>
        </div>
    </div>

    <script>
        let ws;
        let audioContext;
        let mediaRecorder;
        let chunks = [];
        let visualization;
        let isProduct = window.location.host==="cy-deb.xrainchen.top:36000";
        let wssAgent = "cy-deb.xrainchen.top:35555";
        var audioElement = new Audio();
        function preMessage() {
            // 发送初始化消息
            let initmessage = {
                type: "ctrl",
                ctrl: "prev",
                echo: { aaa: "ctrl-prev" }
            };
            // 发送start消息
            ws.send(JSON.stringify(initmessage));
        }
        function nextMessage() {
            // 发送初始化消息
            let initmessage = {
                type: "ctrl",
                ctrl: "next",
                echo: { aaa: "ctrl-next" }
            };
            // 发送start消息
            ws.send(JSON.stringify(initmessage));
        }
        function startWebSocket() {
            var wssUrl = document.getElementById("wssUrl").value;
            if (isProduct) {
                wssUrl = wssUrl.replace("192.168.66.90:15555", "cy-deb.xrainchen.top:35555");
            }
            ws = new WebSocket(wssUrl);
            ws.binaryType = 'arraybuffer';
            ws.onopen = function () {
                appendText("WebSocket 连接成功");
                // 发送初始化消息
                let initmessage = {
                    type: "init",
                    data: {
                        userid: "1111",
                        sn: "863492053403973"
                    },
                    echo: { aaa: "start" }
                };
                // 发送start消息
                ws.send(JSON.stringify(initmessage));
                appendText("发送初始化包" + JSON.stringify(initmessage));
                // 在发送消息后等待1秒
                setTimeout(function () {
                    appendText("等待100毫秒");
                }, 100);
            };

            ws.onmessage = function (event) {
                let audioData = event.data;
                // Assuming you have a function to handle PCM audio data
                appendText("接收到消息" + event.data);
                console.log("Received message:", event.data); // 打印收到的消息内容
                try {
                    var resData = JSON.parse(event.data);
                    if (resData.type && resData.type === "asr") {
                        //http://dev-ai.luomi.cn:25555
                        var videourl = resData.data.url;
                        if (isProduct) {
                            videourl = videourl.replace("dev-ai.luomi.cn:25555", wssAgent)
                        }
                        else {
                            videourl = videourl.replace("http://dev-ai.luomi.cn:25555", "http://192.168.66.90:15555")
                        }
                        playUrl(videourl);
                    }
                }
                catch (error) {
                    console.log(error);
                }
            };

            ws.onerror = function (event) {
                appendText("WebSocket 连接出错" + JSON.stringify(event));
                console.log('WebSocket error:', event);
            };

            ws.onclose = function (event) {
                appendText("WebSocket 连接关闭" + JSON.stringify(event));
                console.log('WebSocket connection closed:', event);
            };
        }

        function stopWebSocket() {
            if (ws) {
                ws.close();
            }
        }

        function sendVideo() {
            // 创建文件选择器
            let input = document.createElement('input');
            input.type = 'file';
            input.accept = '.pcm';
            input.onchange = function (event) {
                let file = event.target.files[0];
                if (!file) {
                    return;
                }
                let reader = new FileReader();
                reader.onload = function (event) {
                    let data = new Uint8Array(event.target.result);
                    sendVideoData(data);
                };
                reader.readAsArrayBuffer(file);
            };
            // 触发文件选择器
            input.click();
        }

        function sendVideoData(data) {
            // 发送开始录音的消息
            let startMessage = {
                type: "start",
                data: {
                    format: "pcm",
                    sample: 16000,
                    sn: "863492053403973"
                }
            };
            ws.send(JSON.stringify(startMessage));
            appendText("发送 start 包" + JSON.stringify(startMessage));
            // 每次发送的最大长度为5k
            let chunkSize = 5 * 1024;
            let offset = 0;
            while (offset < data.byteLength) {
                let chunk = data.slice(offset, offset + chunkSize);
                offset += chunkSize;
                // 发送音频流
                ws.send(chunk);
                appendText("发送音频流 chunk 包,已发送" + offset + "b");
            }
            let finishMessage = {
                type: "finish"
            };
            ws.send(JSON.stringify(finishMessage));
            appendText("发送 finish 包" + JSON.stringify(finishMessage));
        }


        function sendText() {
            var xhr = new XMLHttpRequest();
            var content = document.getElementById("input_area").value;
            var makeVideoUrl = "/api/AiGateway/urlagent?url=" + encodeURI('http://127.0.0.1:15555/api/audio-test?text=' + encodeURI(content))
            xhr.open('GET', makeVideoUrl);
            xhr.responseType = 'blob'; // 将响应类型设置为Blob，以便处理二进制数据
            xhr.onload = function () {
                if (xhr.status === 200) {
                    appendText("音频已生成，开始发送 " + makeVideoUrl);
                    var reader = new FileReader();
                    // 读取Blob对象
                    reader.onload = function () {
                        var data = new Uint8Array(reader.result);
                        sendVideoData(data);
                    };

                    // 将Blob对象转换为Uint8Array
                    reader.readAsArrayBuffer(xhr.response);
                } else {
                    console.error('GET请求失败:', xhr.status);
                }
            };
            // 发送请求
            xhr.send();
        }

        function getCurrentTime() {
            var now = new Date();
            var hour = now.getHours().toString().padStart(2, '0');
            var minute = now.getMinutes().toString().padStart(2, '0');
            var second = now.getSeconds().toString().padStart(2, '0');
            return hour + ":" + minute + ":" + second;
        }
        function appendText(output) {
            // 获取 textarea 元素
            var textarea = document.getElementById("output_area");
            // 追加字符串并换行
            textarea.value += getCurrentTime() + " " + output + "\n";
            textarea.scrollTop = textarea.scrollHeight;
        }
        function clearLog() {
            var textarea = document.getElementById("output_area");
            textarea.value = "";
        }
        function playUrl(url) {
            document.getElementById("audioUrl").value = url;
            audioElement.src = url;
            audioElement.play();
        }
        function playAudio() {
            var audioUrl = document.getElementById("audioUrl").value;
            if (audioUrl.trim() === "") {
                alert("请输入音频URL");
                return;
            }
            playUrl(audioUrl);
        }
        function stopAudio() {
            // 停止播放音频
            audioElement.pause();
            // 重置音频元素的src属性
            audioElement.src = "";
        }
        document.addEventListener("DOMContentLoaded", function () {
            //startWebSocket();
        });
    </script>

</body>
</html>
